package com.zero.xiaodai.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.lowagie.text.pdf.codec.Base64.InputStream;

import sun.misc.BASE64Encoder;

public class OcrUtil {

	// 设置APPID/AK/SK
	public static final String APP_ID = "17608800";
	public static final String API_KEY = "sHu9fb49UV9IIWRTC1ZgY9hi";
	public static final String SECRET_KEY = "ZWeLxqmRAw1lvreoZNX0WRCmz3vl4RQV";

	public static void main(String[] args) {
		test();
	}

	private static void test() {
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		// 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//				client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
//				client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理

		// 可选：设置log4j日志输出格式，若不设置，则使用默认配置
		// 也可以直接通过jvm启动参数设置此环境变量
//				System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

		// 调用接口
		String path = "src/main/resources/image/eom1.png";
		// JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
		JSONObject res = client.accurateGeneral(path, new HashMap<String, String>());
		//JSONObject res = client.form(path, new HashMap<String, String>());
		// client.
		System.out.println(res.toString(2));
	}

	private static void HttpOcr() {
		String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY
				+ "&client_secret=" + SECRET_KEY;
		Map<String, String> param = new HashMap<>();
		param.put("grant_type", "client_credentials");
		param.put("client_id", API_KEY);
		param.put("client_secret", SECRET_KEY);
		// String url="https://aip.baidubce.com/rest/2.0/ocr/v1/form";
		// url=url+"?access_token="+(pageNo-1)*pageSize+"&pageSize="+pageSize;

		Map map = HttpGetData.getData(url, param);
		String token=(String) map.get("access_token");
		System.err.println(token);
		
		url="https://aip.baidubce.com/rest/2.0/ocr/v1/form?access_token="+token;
		
		File f=new File("src/main/resources/image/33.png");
		try {
			FileInputStream in = new FileInputStream("src/main/resources/image/33.png");
			byte[] b=new byte[in.available()];
			in.read(b);
			
			BASE64Encoder encoder = new BASE64Encoder();
	        String strNetImageToBase64 = encoder.encode(b);
	        
	        param.put("image", strNetImageToBase64);
	        
	        map = HttpGetData.getData(url, param);
	        
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
